package com.merugu.school.spring;

import com.merugu.school.beans.StudentBean;
import com.merugu.school.hibernate.Student;
import com.merugu.school.util.SpringUtil;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.logging.Logger;

/**
 * Data access object to access student related data form database
 */
public class StudentDao extends HibernateDaoSupport {

    /**
     * Spring bean name
     */
    private static final String BEAN_NAME = "studentDao";

    /**
     * Logger instance for this class
     */
    private static Logger LOGGER = Logger.getLogger(StudentDao.class.getName());


    /**
     * Saves the student to the database
     *
     * @param studentBean
     */
    public void saveStudent(StudentBean studentBean) {
        LOGGER.info("Creating new student.....");
        Student student = SpringUtil.convert(studentBean);
        getHibernateTemplate().saveOrUpdate(student);

    }

    /**
     * Updates the student details
     *
     * @param studentBean
     */
    public void updateStudent(StudentBean studentBean) {
       LOGGER.info("Updating student " + studentBean.getFirstName());
        Student student = SpringUtil.convert(studentBean);
        getHibernateTemplate().update(student);
    }


    /**
     * Delete student form the database
     *
     * @param studentBean
     */
    public void deleteStudent(StudentBean studentBean) {
        LOGGER.info("Deleting the student ..." + studentBean.getFirstName());
        Student student = SpringUtil.convert(studentBean);
        getHibernateTemplate().delete(student);
    }

    /**
     * Returns the instance of @StudentDao form Spring bean factory.
     *
     * @return StudentDao
     */
    public static StudentDao getStudentDao() {
        return SpringUtil.getBean(BEAN_NAME, StudentDao.class);
    }

}
